package cn.ycq.im.chat.netty;

import cn.ycq.im.http.DefaultHttpRequestHandler;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

@Component
@Slf4j
public class NettyChatServer implements InitializingBean {

    @Value("${server.wsUrl}")
    private String wsUrl;

    @Value("${server.port}")
    private Integer port;

    private EventLoopGroup bossGroup;
    private EventLoopGroup workGroup;

    private ServerBootstrap server;
    private ChannelFuture future;

    public void run() {

        bossGroup = new NioEventLoopGroup(1);
        workGroup = new NioEventLoopGroup(Runtime.getRuntime().availableProcessors() * 8);
        try {
            server = new ServerBootstrap()
                    .group(bossGroup, workGroup)
                    .channel(NioServerSocketChannel.class)
                    .option(ChannelOption.SO_BACKLOG, 128)
                    .childOption(ChannelOption.SO_KEEPALIVE, true)
                    .childHandler(new MyChannelInitializer(wsUrl));
            future = server.bind(new InetSocketAddress(port)).sync();
        } catch (Exception e) {
            throw new RuntimeException("启动服务异常",e);
        }

        log.info("启动成功,listen port {}",port);

    }

    public void sync() throws InterruptedException {
        future.sync();
    }

    public void stop() {
        bossGroup.shutdownGracefully();
        workGroup.shutdownGracefully();
        future.channel().closeFuture();
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        run();
    }
}
